package com.seo.service.transaction.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.seo.mapper.transaction.TransactionMapper;
import com.seo.pojo.transaction.TransactionFlow;
import com.seo.pojo.transaction.TransactionFlowItem;
import com.seo.pojo.transaction.TransactionItem;
import com.seo.service.transaction.sdk.TransactionItemService;
import com.seo.service.transaction.sdk.TransactionService;
import com.seo.pojo.ReturnBody;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class TransactionAmountServiceImpl implements TransactionItemService {

	@Autowired
	private TransactionService transactionService;

	@Autowired
	private TransactionMapper transactionMapper;

	@PostConstruct
	@Override
	public void init() {
		log.info("amount-注册账单科目代理-开始");
		transactionService.put("amount", this);
		log.info("amount-注册账单科目代理-开始");
	}

	@Override
	public ReturnBody saveTransactionFlowItem(String tradeId, TransactionFlow tf, String payMode, BigDecimal amount,
			String itemCode, String state) {
		log.info("[{}]-【保存账单子科目[{}]】", tradeId, itemCode);
		ReturnBody body = ReturnBody.init();

		TransactionItem transactionItem = transactionMapper.getTransactionItemByCode(itemCode);
		if (transactionItem == null) {
			log.error("[{}]-【账单子科目[{}]不存在】", tradeId, itemCode);
			return body.error("账单子科目不存在");
		}

		TransactionFlowItem tfi = new TransactionFlowItem();
		tfi.setTransactionId(tf.getId());
		tfi.setUserId(tf.getUserId());
		tfi.setItemCode("amount");
		tfi.setPayMode(payMode);
		tfi.setState(state);
		tfi.setName("金额");
		tfi.setAmount(amount);
		tfi.setUnit("元");
		tfi.setRatio(new BigDecimal("1"));
		tfi.setEqualAmount(amount);

		int num = transactionMapper.saveTransactionFlowItem(tfi);
		if (num == 0) {
			return body.rollback("账单子科目保存失败");
		}
		return body.success();
	}

	@Override
	public ReturnBody updateTransactionFlowItem(String tradeId, String state, TransactionFlowItem tfi, String payMode) {
		ReturnBody body = ReturnBody.init();

		if (!TransactionFlow.State.no.equals(tfi.getState())) {
			log.error("[{}]-【现金处理】-【现金状态异常】", tradeId);
			return body.rollback("现金处理失败");

		}

		log.info("[{}]-【现金处理】-【默认现金处理】", tradeId);
		Map<String, Object> params = new HashMap<>();
		params.clear();
		params.put("transactionId", tfi.getTransactionId());
		params.put("itemCode", tfi.getItemCode());
		params.put("state", state);
		params.put("oldState", tfi.getState());
		params.put("payMode", payMode);
		int num = transactionMapper.updateTransactionFlowItemState(params);
		if (num == 0) {
			log.error("[{}]-【处理账单】-【更新现金状态、支付方式失败】", tradeId);
			return body.rollback("更新现金状态、支付方式失败");
		}
		return body.success();
	}

}
